package com.example.demo.io.nio.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Description: server socket 服务端程序<br/>
 *
 * @author LLL<br                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               />;
 * @taskId <br/>
 * @Date 2019/5/30 16:26
 * @Version 1.0
 */
@Slf4j
public class EchoServer {

    private int port = 9999;

    private ServerSocket serverSocket;

    public EchoServer() throws IOException {
        serverSocket = new ServerSocket(port);
        log.info("服务端正在启动......");
    }

    public String echo(String msg) {
        return "echo:" + msg;
    }

    private PrintWriter getPrintWriter(Socket socket) throws IOException {
        OutputStream socketOutputStream = socket.getOutputStream();
        return new PrintWriter(socketOutputStream, true);
    }

    private BufferedReader getBufferedReader(Socket socket) throws IOException {
        InputStream socketInputStream = socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketInputStream));
    }

    public void service() {
        while (true) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
                BufferedReader bufferedReader = getBufferedReader(socket);
                PrintWriter printWriter = getPrintWriter(socket);
                String msg = null;
                while ((msg = bufferedReader.readLine()) != null) {
                    printWriter.println(echo(msg));
                    if (msg.equals("bye")) {
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    public static void main(String[] args) throws IOException {
        new EchoServer().service();
    }

}
